package com.wswy.wzcx.module.validator

import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatDialog
import android.util.Base64
import com.blankj.utilcode.util.ImageUtils
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.resp.CaptchaData
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.module.base.onResult
import com.wswy.wzcx.ui.other.TextWatcherIMPL
import kotlinx.android.synthetic.main.dialog_captcha_img.*

class ImgCaptchaDialog(context: Context,private val captchaData: CaptchaData?) : AppCompatDialog(context, R.style.customTransparentDialog2){


    var validCallback:((String?)->Unit)?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_captcha_img)

        setCanceledOnTouchOutside(false)
        setCancelable(false)

        img_captcha.setImageBitmap(ImageUtils.getBitmap(Base64.decode(captchaData?.image?.replaceFirst("data:image/jpeg;base64,",""),Base64.DEFAULT),0))

        ll_btn_valid.normal("验证")

        img_close.onClick {
            validCallback?.invoke(null)
        }

        ll_btn_valid.onClick {
            val code = et_captcha.text?.toString()
            if (!code.isNullOrEmpty()){
                doValid(code)
            }else{

                ToastUtils.showText("请输入验证码")
            }

        }

        et_captcha.addTextChangedListener(object :TextWatcherIMPL(){
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                super.onTextChanged(s, start, before, count)
                ll_btn_valid.isEnabled = !s.isNullOrEmpty()

            }
        })

    }


    private fun doValid(code:String){

        Api.get().validCaptcha(ValidReq(type = IValidator.IMG,uniqueCode = captchaData?.unique,code = code))?.onResult({
            validCallback?.invoke(it?.ticket)
        },{
            ToastUtils.showText(it?.msg)
            validCallback?.invoke(null)
        })

    }

}